package com.godpaper.chessGameHall.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	import com.godpaper.chessGameHall.events.RoomListUpdateEvent;
	import com.godpaper.chessGameHall.events.TryLoginEvent;
	import com.godpaper.chessGameHall.events.UserCountChangeEvent;
	import com.godpaper.chessGameHall.model.LoginModelLocator;
	
	import it.gotoandplay.smartfoxserver.SFSEvent;
	
	import mx.rpc.IResponder;
	
	public class TryLoginCommand extends CommandBase implements ICommand, IResponder
	{
		private var tryLoginEvent:TryLoginEvent;
		private var loginModel:LoginModelLocator = LoginModelLocator.getInstance();
		public function TryLoginCommand()
		{
			super();
		}
		
		override public function execute(event:CairngormEvent):void
		{
			tryLoginEvent  = TryLoginEvent(event);
			this.sfClient.addEventListener(SFSEvent.onLogin,onLogin);
			this.sfClient.login(tryLoginEvent.zone,tryLoginEvent.name,tryLoginEvent.pass);
		}
		
		private function onLogin(event:SFSEvent):void
		{
			if(!event.params.success)
			{
				loginModel.loginStatus = event.params.error;
			}else
			{
				this.sfClient.addEventListener(SFSEvent.onRoomListUpdate,function(event:SFSEvent):void
				{
					var roomListUpdateEvent:RoomListUpdateEvent = new RoomListUpdateEvent(event);
					CairngormEventDispatcher.getInstance().dispatchEvent( roomListUpdateEvent );
				});
				this.sfClient.addEventListener(SFSEvent.onUserCountChange,function(event:SFSEvent):void
				{
					var userCountChangeEvent:UserCountChangeEvent = new UserCountChangeEvent(event);
					CairngormEventDispatcher.getInstance().dispatchEvent( userCountChangeEvent );
				});
			}
		}
		
		
	}
}